import React, { useState, useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
// import { mainStore } from '../stores';
// import { myAxios } from '../axios';
import { Modal, Select,DatePicker } from 'antd';
import { marked } from 'marked';
import './RecStudent.less';
// import moment from 'moment';
const RecStudent = observer(() => {
  // const [messageHistory, setMessageHistory] = useState([]);
  const [messages, setMessages] = useState([]);
  const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [isResponding, setIsResponding] = useState(false);
  
  // 学生推荐表单状态
  const [formData, setFormData] = useState({
    school: '',
    area: '',
    gender: '',
    age: '',
    grade: '',
    subject: '',
    helpType: '',
    rewardMin: '',
    rewardMax: '',
    frequency: '',
    duration: '',
    date: '',
    content: ''
  });
  
  const descriAss = {"stu-rec-expert":"智能推荐"};
  
  const chatContent = useRef(null);
  
  // 配置marked，使链接在新页面打开
  useEffect(() => {
    const renderer = new marked.Renderer();
    const linkRenderer = renderer.link;
    renderer.link = (href, title, text) => {
      const html = linkRenderer.call(renderer, href, title, text);
      return html.replace(/^<a /, '<a target="_blank" rel="noopener noreferrer" ');
    };
    marked.setOptions({ renderer });
  }, []);
  
  const handleScroll = () => {
    if (!chatContent.current) return;
    const { scrollTop, scrollHeight, clientHeight } = chatContent.current;
    setShouldAutoScroll(Math.abs(scrollHeight - scrollTop - clientHeight) <= 1);
  };
  
  const scrollToBottom = () => {
    if (chatContent.current && shouldAutoScroll) {
      chatContent.current.scrollTop = chatContent.current.scrollHeight;
    }
  };
  
  const addMessage = (content, role = 'message-user', thinking = '') => {
    setMessages(prev => [...prev, { content, role, thinking }]);
    setTimeout(scrollToBottom, 0);
  };
  
  const clearChat = () => {
    setMessages([]);
    // setMessageHistory([]);
    // 清除localStorage中的聊天记录
    localStorage.removeItem('recStudentChatHistory');
  };
  
  
  const clearHistoryMsg = async () => {
    Modal.confirm({
      title: '确认清除',
      content: '确定要清除所有聊天记录吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        clearChat();
      }
    });
  };
  
  // 保存聊天记录到localStorage
  const saveChatToLocalStorage = (messages) => {
    try {
      sessionStorage.setItem('recStudentChatHistory', JSON.stringify(messages));
    } catch (error) {
      console.error('保存聊天记录到localStorage失败:', error);
    }
  };
  
  
  // 处理表单输入变化
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 重置表单
  const resetForm = () => {
    setFormData({
      school: '',
      area: '',
      gender: '',
      age: '',
      grade: '',
      subject: '',
      helpType: '',
      rewardMin: '',
      rewardMax: '',
      frequency: '',
      duration: '',
      date: '',
      content: ''
    });
  };
  // const API_URL = 'http://localhost:8090';
  const API_URL = 'http://159.75.133.177:8090';
  // 提交表单进行推荐查询
  const submitRecommendation = () => {
    // 生成推荐查询的prompt
    let promptParts = [];
    
    // 只添加非空字段
    if (formData.school) {
      promptParts.push(`学校：${formData.school}`);
    }
    
    if (formData.area) {
      promptParts.push(`地点：${formData.area}`);
    }
    
    if (formData.gender) {
      promptParts.push(`性别：${formData.gender}`);
    }
    
    if (formData.age) {
      promptParts.push(`年龄：${formData.age}`);
    }
    
    if (formData.grade) {
      promptParts.push(`年级：${formData.grade}`);
    }
    
    if (formData.subject) {
      promptParts.push(`科目：${formData.subject}`);
    }
    
    if (formData.helpType) {
      promptParts.push(`助教类型：${formData.helpType}`);
    }
    
    if (formData.rewardMin && formData.rewardMax) {
      promptParts.push(`志愿奖励区间：${formData.rewardMin}-${formData.rewardMax}`);
    } else if (formData.rewardMin) {
      promptParts.push(`志愿奖励最小值：${formData.rewardMin}`);
    } else if (formData.rewardMax) {
      promptParts.push(`志愿奖励最大值：${formData.rewardMax}`);
    }
    
    if (formData.frequency) {
      promptParts.push(`频率：${formData.frequency}`);
    }
    
    if (formData.duration) {
      promptParts.push(`时长：${formData.duration}`);
    }
    
    if (formData.date) {
      promptParts.push(`发布时间：${formData.date}`);
    }
    
    if (formData.content) {
      promptParts.push(`详细说明：${formData.content}`);
    }
    
    // 如果没有填写任何字段，提示用户
    if (promptParts.length === 0) {
      Modal.warning({
        title: '提示',
        content: '请至少填写一项查询条件',
      });
      return;
    }
    
    // 构建完整prompt
    const prompt = `请根据以下条件推荐合适的学生，如果没有完全符合的，请先说明情况，然后再酌情推荐一些满足部分条件的，一次最多推荐三个：\n${promptParts.join('\n')}\n请详细说明推荐理由和学生特点。`;
    console.log('生成的prompt:', prompt);
    
    // 调用发送消息函数
    sendRecommendationRequest(prompt);
  };
  
  // 发送推荐请求
  const sendRecommendationRequest = async (prompt) => {
    if (isResponding) return;
    
    setIsResponding(true);
    // 不显示用户输入的prompt
    // addMessage(prompt);
    
    try {
      let fullResponse = '';
      let fullThinking = '';
      addMessage('', 'message-ai');
      setIsLoading(true);
          // 兼容性处理 origin
      const origin = window.location.origin || 
      window.location.protocol + '//' + 
      window.location.hostname + 
      (window.location.port ? ':' + window.location.port : '');
      // 使用POST请求调用流式API

      const response = await fetch(`${API_URL}/api/deepseek/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({
          question: prompt,
          localhost: origin,
        }),
      });
      console.log(response)
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');
        // console.log(lines)
        for (const line of lines) {
          // console.log(line)
          if (line.startsWith('data:')) {
            const jsonStr = line.slice(5);
            // console.log(jsonStr)
            if (jsonStr.trim() === '[DONE]') {
              // 处理完成标记
              console.log('最终推荐结果:', fullResponse);
              console.log('流式响应完成');
              continue;
            }
            
            if (jsonStr.trim()) {
              try {
                const jsonData = JSON.parse(jsonStr);
                
                // 处理错误响应
                if (jsonData.error) {
                  console.error('服务器返回错误:', jsonData.error);
                  setMessages(prev => {
                    const last = prev[prev.length - 1];
                    return [...prev.slice(0, -1), { ...last, content: `服务器错误: ${jsonData.error}` }];
                  });
                  continue;
                }
                
                if (jsonData.choices && jsonData.choices[0].delta) {
                  // 处理思考过程（如果有）
                  if (jsonData.choices[0].delta.reasoning_content) {
                    fullThinking += jsonData.choices[0].delta.reasoning_content;
                    setMessages(prev => {
                      const last = prev[prev.length - 1];
                      return [...prev.slice(0, -1), { ...last, thinking: fullThinking }];
                    });
                  }
                  
                  // 处理内容
                  if (jsonData.choices[0].delta.content) {
                    if (fullResponse === '') setIsLoading(false);
                    fullResponse += jsonData.choices[0].delta.content;
                    setMessages(prev => {
                      const newMessages = [...prev.slice(0, -1), { ...prev[prev.length - 1], content: fullResponse }];
                      // 保存到localStorage
                      saveChatToLocalStorage(newMessages);
                      return newMessages;
                    });
                    if(shouldAutoScroll) scrollToBottom();
                  }
                }
              } catch (e) {
                console.error('解析JSON失败:', e, jsonStr);
              }
            }
          }
        }
      }
      
      setIsLoading(false);
      // 不将推荐请求添加到消息历史中
      // setMessageHistory(prev => [...prev, { role: "assistant", content: fullResponse }]);
    } catch (error) {
      console.error('请求失败:', error);
      setMessages(prev => {
        const last = prev[prev.length - 1];
        const newMessages = [...prev.slice(0, -1), { ...last, content: '抱歉，发生了错误: ' + error.message }];
        // 保存到localStorage
        saveChatToLocalStorage(newMessages);
        return newMessages;
      });
    } finally {
      setIsResponding(false);
    }
  };
  
  useEffect(() => {
    // 从localStorage获取历史聊天记录
    try {
      const savedMessages = sessionStorage.getItem('recStudentChatHistory');
      if (savedMessages) {
        setMessages(JSON.parse(savedMessages));
        setTimeout(scrollToBottom, 0);
      }
    } catch (error) {
      console.error('从localStorage获取聊天记录失败:', error);
    }
    
    // 配置marked，使链接在新页面打开
    const renderer = new marked.Renderer();
    const linkRenderer = renderer.link;
    renderer.link = (href, title, text) => {
      const html = linkRenderer.call(renderer, href, title, text);
      return html.replace(/^<a /, '<a target="_blank" rel="noopener noreferrer" ');
    };
    marked.setOptions({ renderer });
  }, []);
  
  return (
    <div className="rec-shell">
      <div className="model-selector">
          <div className='active model-option'>
            {descriAss['stu-rec-expert']}
          </div>
        <div className="clear-txt" onClick={clearHistoryMsg}>清除记录</div>
      </div>
      <div className="content" ref={chatContent} onScroll={handleScroll}>
        {messages.map((message, index) => (
          <div key={index} className={`message ${message.role}`}>
            {message.thinking && (
              <div className="thinking-content">
                <div className="thinking-title">思考过程:</div>
                <div dangerouslySetInnerHTML={{ __html: marked.parse(message.thinking) }} />
              </div>
            )}
            {message.role === 'message-ai' && message.content === '' && isLoading && (
              <div className="loading-animation">
                <div className="dot"></div>
                <div className="dot"></div>
                <div className="dot"></div>
              </div>
            )}
            <div className="message-content">
              <div dangerouslySetInnerHTML={{ __html: marked.parse(message.content) }} />
              {message.role === 'message-ai' && !isLoading && isResponding && index === messages.length - 1 && (
                <div style={{ position: 'relative', right: 0 }} className="loading-animation">
                  <div className="dot"></div>
                  <div className="dot"></div>
                  <div className="dot"></div>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
      <div className="input-content">
        <div className="form-container">
          <div className="form-row">
            <div className="form-group">
              <label>科目：</label>
              <input 
                type="text" 
                name="subject" 
                value={formData.subject} 
                onChange={handleFormChange} 
                placeholder="请输入科目"
              />
            </div>
            <div className="form-group">
              <label>地点：</label>
              <input 
                type="text" 
                name="area" 
                value={formData.area} 
                onChange={handleFormChange} 
                placeholder="请输入地点"
              />
            </div>
            <div className="form-group">
              <label>志愿奖励：</label>
              <div className="reward-range">
                <input 
                  type="number" 
                  name="rewardMin" 
                  value={formData.rewardMin} 
                  onChange={handleFormChange} 
                  placeholder="最小值"
                  style={{ width: '35%' }}
                />
                <span style={{ margin: '0 5px' }}>-</span>
                <input 
                  type="number" 
                  name="rewardMax" 
                  value={formData.rewardMax} 
                  onChange={handleFormChange} 
                  placeholder="最大值"
                  style={{ width: '35%' }}
                />
              </div>
            </div>
          </div>
          
          <div className="form-row">
            <div className="form-group">
              <label>性别：</label>
              <Select
                name="gender"
                value={formData.gender}
                onChange={(value) => handleFormChange({ target: { name: 'gender', value } })}
                placeholder="请选择性别"
                style={{ width: '100%',borderRadius: '4px',height: '38px' }}
              >
                <Select.Option value="">请选择</Select.Option>
                <Select.Option value="男">男</Select.Option>
                <Select.Option value="女">女</Select.Option>
              </Select>
            </div>
            <div className="form-group">
              <label>助教类型：</label>
              <Select
                name="helpType"
                value={formData.helpType}
                onChange={(value) => handleFormChange({ target: { name: 'helpType', value } })}
                placeholder="请选择助教类型"
                style={{ width: '100%',borderRadius: '4px',height: '38px' }}
              >
                <Select.Option value="">请选择</Select.Option>
                <Select.Option value="线上">线上</Select.Option>
                <Select.Option value="线下">线下</Select.Option>
              </Select>
            </div>
            <div className="form-group">
              <label>年龄：</label>
              <input 
                type="number" 
                name="age" 
                value={formData.age} 
                onChange={handleFormChange} 
                placeholder="请输入年龄"
                style={{ width: '120px'}}
              />
            </div>
            <div className="form-group">
              <label>年级：</label>
              <input 
                type="text" 
                name="grade" 
                value={formData.grade} 
                onChange={handleFormChange} 
                placeholder="请输入年级"
                // style={{ width: '120px'}}
              />
            </div>
          </div>
          
          <div className="form-row">
            <div className="form-group">
              <label>频率(次/周)：</label>
              <input 
                type="text" 
                name="frequency" 
                value={formData.frequency} 
                onChange={handleFormChange} 
                placeholder="例如：每周三次"
                style={{ width: '200px'}}
              />
            </div>
            <div className="form-group">
              <label>时长(时/次)：</label>
              <input 
                type="text" 
                name="duration" 
                value={formData.duration} 
                onChange={handleFormChange} 
                placeholder="例如：2小时/次"
                style={{ width: '150px'}}
              />
            </div>
            <div className="form-group">
              <label>发布时间：</label>
              <input 
                type="date"
                name="date" 
                value={formData.date} 
                onChange={handleFormChange} 
                placeholder="请输入"
              />
              {/* <DatePicker>

              </DatePicker> */}
            </div>
          </div>
          
          <div className="form-row">
            <div className="form-group full-width">
              <label>详细说明：</label>
              <textarea 
                name="content" 
                value={formData.content} 
                onChange={handleFormChange} 
                placeholder="请输入详细说明"
                rows="3"
              />
            </div>
            <div className="form-buttons">
              <button className="reset-btn" onClick={resetForm}>重置表单</button>
              <button className="submit-btn" onClick={submitRecommendation}>检索推荐</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
});

export default RecStudent;